package com.micro.trace.log.filter;

import org.springframework.util.StreamUtils;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;

/**
 * 自定义 HttpServletRequestWrapper
 *
 * @see HttpServletRequestWrapper
 */
class RequestCachingRequestWrapper extends ContentCachingRequestWrapper {

    private final ServletInputStream inputStream;

    public RequestCachingRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        this.inputStream = request.getInputStream();
    }

    @Override
    public byte[] getContentAsByteArray() {
        if (!this.inputStream.isFinished()) {
            try {
                return StreamUtils.copyToByteArray(this.inputStream);
            } catch (IOException e) {
                return super.getContentAsByteArray();
            }
        }
        return super.getContentAsByteArray();
    }

}
